<?php


namespace App\W7OpenTracing;


use OpenTracing\NoopTracer;
use Psr\Log\LoggerInterface;
use Zipkin\Endpoint;
use Zipkin\Reporter;
use Zipkin\Reporters\Http;
use Zipkin\Sampler;
use Zipkin\Samplers\BinarySampler;
use Zipkin\TracingBuilder;

class TracerFactory
{
    public function enable()
    {
        return config('opentracing.enable', true);
    }

    public function serviceName()
    {
        return config('opentracing.service_name');
    }

    protected function endpoint()
    {
        return config('opentracing.zipkin.http_endpoint');
    }

    public function makeTracer(): \OpenTracing\Tracer
    {
        if (!$this->enable()) {
            return new NoopTracer();
        }

        $tracing = TracingBuilder::create()
            ->havingLocalEndpoint($this->makeEndPoint())
            ->havingSampler($this->makeSampler())
            ->havingReporter($this->makeReporter())
            ->build();

        return new \ZipkinOpenTracing\Tracer($tracing);
    }

    /**
     * @return Sampler
     */
    protected function makeSampler(): Sampler
    {
        return BinarySampler::createAsAlwaysSample();
    }

    /**
     * @return Reporter
     */
    protected function makeReporter(): Reporter
    {
        return new Http(
            ['endpoint_url' => $this->endpoint()],
            null,
            app()->make(LoggerInterface::class)
        );
    }

    /**
     * @return Endpoint
     */
    protected function makeEndPoint(): Endpoint
    {
        return Endpoint::create($this->serviceName(), null, null, null);
    }


}
